/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.RedirectResolution;
import org.apache.commons.beanutils.BeanComparator;
import org.xptracker.domain.*;
import org.xptracker.persistence.PersistenceListener;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.port.PortableFields;
import org.xptracker.port.TypeFactory;
import org.xptracker.test.IntegrationTest;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class AdminActionBeanTest extends IntegrationTest {
  private File file;
  private AdminActionBean bean;
  private List<Message> messages;
  private static final String BIG_FILE = "\"summary\",\"queue\",\"lastModified\",\"state\",\"severity\",\"customers\",\"estimate\",\"size\",\"creator\",\"completedDate\",\"description\",\"categories\",\"dueDate\"\n" +
      "\"Test Summary\",,,\"dreaming\",\"warm\",\"MyCustomer\",0,\"medium\",\"jeff\",,\"Some short description\",\"Funjet Travel\",\n" +
      "\"Fun Summary\",,,\"inProcess\",\"cold\",\"Somebody\",0,\"medium\",\"jeff\",,\"Another Description\",\"Neat,Stuff\",";

  private User currentUser;

  protected void beforeInjection(List<Module> modules, List<PersistenceListener> listeners) throws Exception {
    modules.add(new AbstractModule() {
      protected void configure() {
        bind(new TypeLiteral<TypeFactory<Story>>() {
        }).toInstance(new TypeFactory<Story>(PortableFields.makeStoryFields()));
        bind(new TypeLiteral<TypeFactory<User>>() {
        }).toInstance(new TypeFactory<User>(PortableFields.makeUserFields()));
      }
    });

    file = File.createTempFile("test", ".csv");
    FileOutputStream out = new FileOutputStream(file);
    out.write(BIG_FILE.getBytes());
    out.close();
  }

  protected void afterInjection(Injector injector) {
    super.afterInjection(injector);
    bean = new AdminActionBean() {
      protected RedirectResolution returnToAdminPage() {
        return null;
      }
    };
    messages = new ArrayList<Message>();
    ActionBeanContext beanContext = new ActionBeanContext() {
      public List<Message> getMessages() {
        return messages;
      }

      public List<Message> getMessages(String string) {
        return messages;
      }
    };
    bean.setContext(beanContext);
    injector.injectMembers(bean);
    
    injector.injectMembers(new DomainUtil());
  }

  protected void subTeardown() throws Exception {
    file.delete();
  }

  protected User getCurrentUser() {
    return currentUser;
  }

  public void testSimpleImport() throws Exception {
    mgr.inTransaction(new PersistenceManager.UpdateHandler<String>() {
      public String doUpdate(PersistenceManager.UpdateReceiver receiver) {
        User user = new User("jeff");
        receiver.insert(user);
        currentUser = user;
        return user.getId();
      }
    });

    FileBean fileBean = new FileBean(file, "test.csv", "text/csv");
    try {
      bean.setFileBean(fileBean);
      bean.setImportType(AdminActionBean.Type.stories);
      bean.doImport();

      Domain domain = new Domain(mgr);
      List<Story> stories = domain.listStories();
      //noinspection unchecked
      Collections.sort(stories, new BeanComparator("idLong"));
      assertEquals(2, stories.size());
      Story s = domain.fetchStory(stories.get(0).getId());
      assertEquals("Test Summary", s.getSummary());
      assertEquals(State.dreaming, s.getState());
      assertEquals(Severity.warm, s.getSeverity());
      assertEquals("MyCustomer", s.getCustomers().iterator().next().getName());
      assertEquals(Size.medium, s.getSize());
      assertEquals("jeff", s.getCreator().getUsername());
      assertEquals("Some short description", s.getDescription());
      assertEquals("Funjet Travel", s.getCategories().get(0).getName());
    } finally {
      fileBean.delete();
    }
  }
}
